<template>
  <div class="page">
    <div class="content">
      <van-nav-bar
          title="维修安排"
          left-text="返回"
          left-arrow
          @click-left="handleBack"
      />
      <!-- 选项卡 -->
      <t-tabs v-model="currentTab">
        <t-tab-panel value="first">
          <template #label>
            <div>你的任务</div>
          </template>
        </t-tab-panel>
        <t-tab-panel value="second">
          <template #label>
            <div>新任务</div>
          </template>
        </t-tab-panel>
      </t-tabs>

      <!-- 分割线 -->
      <t-divider class="divider"/>

      <!-- 你的任务卡片 -->
      <el-card v-if="currentTab === 'first'" style="max-width: 480px; margin: 4px 0" v-for="task in tasks" :key="task.taskId">
        <template #header>
          <div class="card-header">
            <span>任务ID: {{ task.taskId }}</span>
            <span class="card-header-status">{{ task.status }}</span>
          </div>
        </template>
        <p class="text-base">故障报修ID: {{ task.failureRepairId }}</p>
        <p class="text-base">维修人员ID: {{ task.repairPersonnelId }}</p>
        <p class="text-base">任务分配时间: {{ task.assignedTime }}</p>
        <p class="text-base">任务接受时间: {{ task.acceptanceTime }}</p>
        <div class="el-card_footer">
          <div class="footer-buttons">
            <el-button plain @click="viewDetails(task)" type="primary">查看详情</el-button>
          </div>
        </div>
      </el-card>

      <!-- 新任务卡片 -->
      <el-card v-if="currentTab === 'second'" style="max-width: 480px; margin: 4px 0" v-for="task in newTasks" :key="task.taskId">
        <template #header>
          <div class="card-header">
            <span>任务ID: {{ task.taskId }}</span>
            <span class="card-header-status_2">{{ task.status }}</span>
          </div>
        </template>
        <p class="text-base">故障报修ID: {{ task.failureRepairId }}</p>
        <p class="text-base">维修人员ID: {{ task.repairPersonnelId }}</p>
        <p class="text-base">任务分配时间: {{ task.assignedTime }}</p>
        <div class="el-card_footer">
          <div class="footer-buttons">
            <el-button type="primary" plain @click="viewDetails(task)">查看详情</el-button>
            <el-button type="primary" @click="acceptTask(task.taskId)">接受任务</el-button>
          </div>
        </div>
      </el-card>

      <!-- 维修安排详情抽屉 -->
      <el-drawer v-model="drawer1" :direction="direction" size="50%">
        <template #header>
          <h4>故障详情</h4>
        </template>
        <template #default>
          <p class="text-base">故障报修ID: {{ taskDetails.failureRepairId }}</p>
          <p class="text-base">标题: {{ taskDetails.title }}</p>
          <p class="text-base">维修类型: {{ taskDetails.type }}</p>
          <p class="text-base">维修地址: {{ taskDetails.repairAddress }}</p>
          <p class="text-base">故障描述: {{ taskDetails.faultDescription }}</p>
          <p class="text-base">报修人联系电话: {{ taskDetails.contactNumber }}</p>
        </template>
      </el-drawer>

      <!-- 接受任务对话框 -->
      <el-dialog v-model="centerDialogVisible" title="接受任务" width="300" center>
        <span>确定接受此任务吗？</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmAcceptTask">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
import { createApp, ref, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import TDesign from 'tdesign-mobile-vue';
import ElementPlus, { ElMessage } from 'element-plus';
import 'tdesign-mobile-vue/es/style/index.css';
import 'element-plus/dist/index.css';
import axios from 'axios';
import App from "@/App.vue";

const app = createApp(App);
app.use(TDesign);
app.use(ElementPlus);

const router = useRouter();
const store = useStore();
const currentTab = ref('first'); // 默认显示第一个选项卡
const tasks = ref([]);
const newTasks = ref([]);
const taskDetails = ref({});
const drawer1 = ref(false);
const direction = ref('btt');
const centerDialogVisible = ref(false);
const selectedTaskId = ref(null);
const user = store.getters.user; // 获取登录用户信息

// 页面加载时获取任务数据
onMounted(async () => {
  await fetchTasks();
});

// 监听选项卡变化，重新获取任务数据
watch(currentTab, async (newValue) => {
  await fetchTasks();
});
// 返回首页
const handleBack = () => {
  router.back('/technician/home');
};
// 获取任务数据
const fetchTasks = async () => {
  try {
    if (currentTab.value === 'first') {
      const response = await axios.get(`http://localhost:8002/repair-tasks/selectAll/${user.repairPersonnelId}/正在处理`);
      tasks.value = response.data;
    } else {
      const response = await axios.get(`http://localhost:8002/repair-tasks/selectAll/${user.repairPersonnelId}/待接受`);
      newTasks.value = response.data;
    }
  } catch (error) {
    console.error('获取任务失败:', error);
  }
};
// 查看任务详情
const viewDetails = async (task) => {
  console.log('当前查看的故障报修ID',task.failureRepairId)
  try{
    const response = await axios.get(`http://localhost:8001/failure-repair/selectById/${task.failureRepairId}`);
    taskDetails.value = response.data;
  } catch (error) {
    console.error('获取故障报修信息失败:', error);
  }
  drawer1.value = true;
}
// 接受任务
const acceptTask = (taskId) => {
  selectedTaskId.value = taskId;
  centerDialogVisible.value = true;
};
// 确认接受任务
const confirmAcceptTask = async () => {
  try {
    const response = await axios.put(`http://localhost:8002/repair-tasks/acceptTask/${selectedTaskId.value}`);
    if (response.data) {
      ElMessage({
        message: '接受成功',
        type: 'success'
      });
      await fetchTasks();
    } else {
      ElMessage({
        message: '接受失败',
        type: 'error'
      });
    }
    centerDialogVisible.value = false;
  } catch (error) {
    console.error('接受任务失败:', error);
    ElMessage({
      message: '接受失败，请重试',
      type: 'error'
    });
    centerDialogVisible.value = false;
  }
};
</script>

<style scoped>
.page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
}

.content {
  flex: 1;
  padding: 20px;
}

.card-header-status {
  float: right;
  color: forestgreen;
  font-size: 14px;
}

.el-card_footer .footer-buttons .el-button:active {
  background-color: #3a8ee6;
  transform: scale(0.95);
}

.footer-buttons {
  display: flex;
  justify-content: flex-end;
}

.card-header-status_2 {
  float: right;
  color: brown;
  font-size: 12px;
}

.divider {
  margin: 10px 0;
}

.center-text {
  text-align: center;
}


.text-base {
  font-size: 14px;
}
</style>
